<?php

namespace app\admin\controller;

use app\common\model\ClassModel;
use app\common\model\GradeModel;
use app\common\model\RelClassModel;
use app\common\model\RelGradeModel;
use app\common\model\RelSchoolModel;
use app\common\model\SchoolModel;
use app\common\model\TableCustomFieldModel;
use app\common\model\UserAttrModel;
use app\common\model\UserLogModel;
use app\common\model\UserModel;

class User extends Common
{
    /**
     * 添加用户
     * @author 贺强
     * @time   2022/9/1 9:07
     */
    public function add()
    {
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            if (empty($param['username']) || empty($param['mobile']) || empty($param['nickname']) || empty($param['password']) || empty($param['category']) || empty($param['name']) || empty($param['idcard'])) {
                return ajax('参数缺失', 101);
            }
            $param['password'] = get_md5_password($param['password']);
            $count = UserModel::getCount(['username' => $param['username']]);
            if ($count) {
                return ajax('账号已存在', 102);
            }
            $count = UserModel::getCount(['mobile' => $param['mobile']]);
            if ($count) {
                return ajax('手机号已存在', 103);
            }
            unset($param['pwd1']);
            $param['status'] = 1;
            $param['login_time'] = 0;
            $param['login_count'] = 0;
            $param['mtime'] = 0;
            $param['login_ip'] = '';
            $res = UserModel::add($param);
            if (!$res) {
                return ajax('添加失败', 400);
            }
            return ajax('添加成功');
        }
        $category = get_user_category();
        return view('', compact('category'));
    }

    /**
     * 修改用户
     * @author 贺强
     * @time   2022/9/1 9:07
     */
    public function edit()
    {
        $id = $this->request->param('id', '');
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            if (empty($param['username']) || empty($param['mobile']) || empty($param['nickname']) || empty($param['category']) || empty($param['name']) || empty($param['idcard'])) {
                return ajax('参数缺失', 101);
            }
            $count = UserModel::getCount([['id', '!=', $id], ['username', '=', $param['username']]]);
            if ($count) {
                return ajax('账号已存在', 102);
            }
            $count = UserModel::getCount([['id', '!=', $id], ['mobile', '=', $param['mobile']]]);
            if ($count) {
                return ajax('手机号已存在', 103);
            }
            if (!empty($param['password'])) {
                $param['password'] = get_md5_password($param['password']);
            } else {
                unset($param['password']);
            }
            $res = UserModel::modify($param, ['id' => $id]);
            if (!$res) {
                return ajax('修改失败', 400);
            }
            return ajax('修改成功');
        }
        $user = UserModel::getModel(['id' => $id], true, '', 0);
        $category = get_user_category();
        $status = get_user_status();
        return view('', compact('user', 'category', 'status'));
    }

    /**
     * 修改扩展资料
     * @author 贺强
     * @time   2022/9/24 11:45
     */
    public function editextend()
    {
        $id = $this->request->param('id', '');
        if (empty($id)) {
            $this->error('非法参数');
        }
        $user = UserModel::getModel(['id' => $id], ['category', 'user_attr'], '', 0);
        $user_attr = !empty($user['user_attr']) ? json_decode($user['user_attr'], true) : [];
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            unset($param['id']);
            if (empty($param)) {
                return ajax('没有任何修改', 102);
            }
            $user_category = $user['category'];
            // 变更用户的学校、年级、班级
            if (!empty($param['school_id'])) {
                $rs = RelSchoolModel::getModel(['user_id' => $id], ['school_id']);
                if (empty($rs)) {
                    // 如果没加入过此学校，则建立学校和用户关系，并把学校人数加 1
                    $res = RelSchoolModel::add(['school_id' => $param['school_id'], 'user_id' => $id, 'user_category' => $user_category, 'mtime' => 0]);
                    if ($res) {
                        SchoolModel::increment('count', ['id' => $param['school_id']]);
                    }
                } elseif ($rs['school_id'] !== $param['school_id']) {
                    // 如果是变更学校，则修改学校和用户关系，并把原学校人数减 1
                    $res = RelSchoolModel::modify(['school_id' => $param['school_id']], ['user_id' => $id]);
                    if ($res) {
                        SchoolModel::decrement('count', ['id' => $rs['school_id']]);
                        SchoolModel::increment('count', ['id' => $param['school_id']]);
                    }
                }
                if (!empty($param['grade_id'])) {
                    $rg = RelGradeModel::getModel(['user_id' => $id], ['grade_id']);
                    if (empty($rg)) {
                        // 如果没加入过此年级，则建立年级和用户关系，并把年级人数加 1
                        $res = RelGradeModel::add(['school_id' => $param['school_id'], 'grade_id' => $param['grade_id'], 'user_id' => $id, 'user_category' => $user_category, 'mtime' => 0]);
                        if ($res) {
                            GradeModel::increment('count', ['id' => $param['grade_id']]);
                        }
                    } elseif ($rg['grade_id'] !== $param['grade_id']) {
                        // 如果是变更年级，则修改年级和用户关系，并把原年级人数减 1
                        $res = RelGradeModel::modify(['school_id' => $param['school_id'], 'grade_id' => $param['grade_id']], ['user_id' => $id]);
                        if ($res) {
                            GradeModel::decrement('count', ['id' => $rg['grade_id']]);
                            GradeModel::increment('count', ['id' => $param['grade_id']]);
                        }
                    }
                    if (!empty($param['class_id'])) {
                        $rc = RelClassModel::getModel(['user_id' => $id], ['class_id']);
                        if (empty($rc)) {
                            // 如果没加入过此班级，则建立班级和用户关系，并把班级人数加 1
                            $res = RelClassModel::add(['school_id' => $param['school_id'], 'grade_id' => $param['grade_id'], 'class_id' => $param['class_id'], 'user_id' => $id, 'user_category' => $user_category, 'mtime' => 0]);
                            if ($res) {
                                ClassModel::increment('count', ['id' => $param['class_id']]);
                            }
                        } elseif ($rc['class_id'] !== $param['class_id']) {
                            // 如果是变更班级，则修改互用 用户关系，并把原班级人数减 1
                            $res = RelClassModel::modify(['school_id' => $param['school_id'], 'grade_id' => $param['grade_id'], 'class_id' => $param['class_id']], ['user_id' => $id]);
                            if ($res) {
                                ClassModel::decrement('count', ['id' => $rc['class_id']]);
                                ClassModel::increment('count', ['id' => $param['class_id']]);
                            }
                        }
                    } else {
                        // 如果班级为空，则删除用户的班级关系
                        RelClassModel::delByWhere(['user_id' => $id]);
                        // 班级人数减 1
                        ClassModel::decrement('count', ['id' => $user_attr['class_id'] ?? '']);
                    }
                } else {
                    // 如果年级为空，则删除用户的年级、班级关系
                    RelGradeModel::delByWhere(['user_id' => $id]);
                    RelClassModel::delByWhere(['user_id' => $id]);
                    // 年级、班级人数减 1
                    GradeModel::decrement('count', ['id' => $user_attr['grade_id'] ?? '']);
                    ClassModel::decrement('count', ['id' => $user_attr['class_id'] ?? '']);
                }
            } else {
                // 如果学校为空，则删除用户的学校、年级、班级关系
                RelSchoolModel::delByWhere(['user_id' => $id]);
                RelGradeModel::delByWhere(['user_id' => $id]);
                RelClassModel::delByWhere(['user_id' => $id]);
                // 学校、年级、班级人数据减 1
                SchoolModel::decrement('count', ['id' => $user_attr['school_id'] ?? '']);
                GradeModel::decrement('count', ['id' => $user_attr['grade_id'] ?? '']);
                ClassModel::decrement('count', ['id' => $user_attr['class_id'] ?? '']);
            }
            foreach ($param as $k => $v) {
                if (!empty($v)) {
                    // 把每个属性的变更记录到用户属性表
                    $attr = UserAttrModel::getModel([['user_id', '=', $id], ['attr_name', '=', $k]]);
                    if (!empty($attr)) {
                        if ($attr['attr_value'] != $v) {
                            $attr['attr_value'] = $v;
                            $attr['mtime'] = time();
                            UserAttrModel::modify($attr);
                        }
                    } else {
                        $data = ['user_id' => $id, 'attr_name' => $k, 'attr_value' => $v, 'ctime' => time(), 'mtime' => 0];
                        UserAttrModel::add($data);
                    }
                } else {
                    // 如果属性值为空，则删除用户的该属性
                    UserAttrModel::delByWhere([['user_id', '=', $id], ['attr_name', '=', $k]]);
                    unset($param[$k]);
                }
            }
            // 保存用户扩展资料
            $user['user_attr'] = json_encode($param);
            $user['mtime'] = time();
            $res = UserModel::modify($user, ['id' => $id]);
            if (!$res) {
                return ajax('修改失败', 400);
            }
            return ajax('修改成功');
        }
        // 学校下拉框
        $school = SchoolModel::getList(['status' => 1], ['id', 'school_name']);
        $grade = [];
        // 如果用户有学校，则年级下拉框默认展示用户学校的年级
        if (!empty($user_attr['school_id'])) {
            $grade = GradeModel::getList(['school_id' => $user_attr['school_id']], ['id', 'grade_name']);
        }
        $banji = [];
        // 如果用户有年级，则班级下拉框默认展示用户年级的班级
        if (!empty($user_attr['grade_id'])) {
            $banji = ClassModel::getList(['grade_id' => $user_attr['grade_id']], ['id', 'class_name']);
        }
        $nations = config('app.nations');
        $fields = TableCustomFieldModel::getList(['table_name' => UserModel::tableName()], true, '', ['sort' => 'asc']);
        foreach ($fields as &$field) {
            if (in_array($field['field_type'], ['radio', 'select'])) {
                $field_value = json_decode($field['field_value'], true);
                $field['field_value'] = array_column($field_value, 'value', 'key');
            }
        }
        return view('extend', compact('school', 'grade', 'banji', 'user_attr', 'nations', 'fields'));
    }

    /**
     * 用户列表
     * @author 贺强
     * @time   2022/3/22 16:52
     */
    public function lists()
    {
        $where = [];
        $param = $this->request->param();
        // print_r($param);exit;
        if (!empty($param['keyword'])) {
            $where[] = ['username|mobile', 'like', "%{$param['keyword']}%"];
        } else {
            $param['keyword'] = '';
        }
        //按状态条件搜索
        if (isset($param['status']) && is_numeric($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        } else {
            $param['status'] = -1;
        }
        $order = ['login_time' => 'desc'];
        if (!empty($param['sort_field'])) {
            $order = [$param['sort_field']];
            if (!empty($param['sort_type'])) {
                $order = [$param['sort_field'] => $param['sort_type']];
            }
        }
        // 分页参数
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
        $list = UserModel::getList($where, true, [$page, $pagesize], $order);
        foreach ($list as &$item) {
            $item['status_txt'] = get_user_status(intval($item['status']));
            format_datetime($item['login_time']);
            format_datetime($item['ctime']);
            format_datetime($item['mtime']);
            if (!empty($item['avatar']) && preg_match("/^upload*/", $item['avatar'])) {
                $item['avatar'] = '/' . str_replace('\\', '/', $item['avatar']);
            }
        }
        if ($this->request->isAjax()) {
            return ajax('获取成功', 200, $list);
        }
        $count = UserModel::getCount($where);
        $pages = ceil($count / $pagesize);
        $status = get_user_status();
        return view('list', compact('list', 'status', 'pages', 'count', 'param'));
    }

    /**
     * 用户登录日志
     * @author 贺强
     * @time   2023/3/25 21:10
     */
    public function logs()
    {
        $where = [];
        $param = $this->request->param();
        if (!empty($param['user_id'])) {
            $where[] = ['user_id', '=', $param['user_id']];
        } else {
            $param['user_id'] = '';
        }
        if (!empty($param['mobile'])) {
            $where[] = ['mobile', 'like', "%{$param['mobile']}%"];
        } else {
            $param['mobile'] = '';
        }
        if (!empty($param['ip'])) {
            $where[] = ['ip', 'like', "%{$param['ip']}%"];
        } else {
            $param['ip'] = '';
        }
        if (!empty($param['ctime'])) {
            $ctime = strtotime($param['ctime']);
            $etime = $ctime + 86400;
            $where[] = ['ctime', '>=', $ctime];
            $where[] = ['ctime', '<', $etime];
        } else {
            $param['ctime'] = '';
        }
        $order = ['ctime' => 'desc'];
        if (!empty($param['sort_field'])) {
            $order = [$param['sort_field']];
            if (!empty($param['sort_type'])) {
                $order = [$param['sort_field'] => $param['sort_type']];
            }
        }
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
        $today = $param['today'] ?? true;
        if ($today) {
            UserLogModel::$datatable = 'user_log_' . date('Ymd');
            UserLogModel::$elastic = 0;
        }
        $list = UserLogModel::getList($where, true, [$page, $pagesize], $order);
        if (!empty($list) && empty($list['code'])) {
            foreach ($list as &$item) {
                if ($item['ctime']) {
                    format_timestamp($item['ctime']);
                }
            }
        }
        if ($this->request->isAjax()) {
            return ajax('获取成功', 200, $list);
        }
        $count = UserLogModel::getCount($where);
        $pages = ceil($count / $pagesize);
        $users = UserModel::getList(['status' => 1], ['id', 'username']);
        return view('logs', compact('list', 'users', 'pages', 'count', 'param', 'today'));
    }

    /**
     * 根据ID删除
     * @author 贺强
     * @time   2022/9/2 16:41
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error('非法操作');
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $id = $this->request->post('id', '');
        if (empty($id)) {
            return ajax('非法参数', 101);
        }
        $res = UserModel::delById($id);
        if (!$res) {
            return ajax('删除失败', 400);
        }
        return ajax('删除成功');
    }

    /**
     * 用户详情
     * @author 贺强
     * @time   2022/9/24 17:29
     */
    public function detail()
    {
        $id = $this->request->get('id', '');
        $user = UserModel::getModel(['id' => $id], true, '', 0);
        if (preg_match("/^upload*/", $user['avatar'])) {
            $user['avatar'] = '/' . str_replace('\\', '/', $user['avatar']);
        }
        format_datetime($user['login_time']);
        $user_attr = !empty($user['user_attr']) ? json_decode($user['user_attr'], true) : [];
        $category = get_user_category();
        $status = get_user_status();
        $arr = ['school_id' => '所属学校ID', 'school_name' => '所属学校', 'grade_id' => '所属年级ID', 'grade_name' => '所属年级', 'class_id' => '所属班级ID', 'class_name' => '所属班级', 'nation' => '民族'];
        $fields = TableCustomFieldModel::getList(['table_name' => UserModel::tableName()]);
        $fields = array_column($fields, 'field_txt', 'field_name');
        $arr = array_merge($arr, $fields);
        return view('detail', compact('user', 'category', 'status', 'user_attr', 'arr'));
    }

    /**
     * 设置用户
     * @author 贺强
     * @time   2022/3/22 16:52
     */
    public function operate()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            return ajax('非法参数', 101);
        }
        $type = $this->request->post('type');
        if (empty($type)) {
            return ajax('非法操作', 102);
        }
        if ($type === 'del' || $type === 'delAll') {
            $res = UserModel::delByWhere([['id', 'in', $ids]]);
            if (!$res) {
                return ajax('删除失败', 400);
            }
            return ajax('删除成功');
        } elseif ($type === 'disable' || $type === 'disableAll') {
            $field = 'status';
            $value = 4;
            $msg = '禁用';
        } elseif ($type === 'enable' || $type == 'enableAll') {
            $field = 'status';
            $value = 1;
            $msg = '启用';
        } elseif ($type == 'refresh' || $type == 'refreshAll') {
            $ids = implode(',', $ids);
            $table = UserModel::tableName();
            $attr_field = 'user_attr';
            $field = 'user_id';
            $data = compact('table', 'ids', 'attr_field', 'field');
            queue('app\\common\\job\\EsJob@sync_attr_data', $data);
            return ajax('重刷成功');
        } else {
            return ajax('非法操作', 103);
        }
        $res = UserModel::modify([$field => $value], [['id', 'in', $ids]]);
        if ($res) {
            return ajax($msg . '成功');
        } elseif ($res === false) {
            return ajax($msg . '失败', 400);
        } else {
            return ajax('该账号已' . $msg, 201);
        }
    }

    /**
     * ajax 获取年级
     * @author 贺强
     * @time   2022/9/27 8:52
     */
    public function get_grade()
    {
        if (!$this->request->isAjax()) {
            return ajax('非法操作', 101);
        }
        $school_id = $this->request->post('school_id', '');
        if (empty($school_id)) {
            return ajax('参数缺失', 102);
        }
        $where = [['school_id', '=', $school_id], ['status', '=', 1]];
        $list = GradeModel::getList($where, ['id', 'grade_name']);
        if (empty($list)) {
            return ajax('暂无数据', 103);
        }
        return ajax('获取成功', 200, $list);
    }

    /**
     * ajax 获取班级
     * @author 贺强
     * @time   2022/9/27 11:30
     */
    public function get_banji()
    {
        if (!$this->request->isAjax()) {
            return ajax('非法操作', 101);
        }
        $grade_id = $this->request->post('grade_id', '');
        if (empty($grade_id)) {
            return ajax('参数缺失', 102);
        }
        $where = [['grade_id', '=', $grade_id], ['status', '=', 1]];
        $list = ClassModel::getList($where, ['id', 'class_name']);
        if (empty($list)) {
            return ajax('暂无数据', 103);
        }
        return ajax('获取成功', 200, $list);
    }
}
